<?php
namespace app\mobile\controller;

use app\model\Theme; 
use app\model\Worker; 

class WDaping extends Base
{
    public function W_daping()
    {
global $_G, $_P;
$op = !empty($_P['op']) ? $_P['op'] : 'display';
// $fans = $this->checkuser();
$themeid = intval($_P['themeid']);
if($themeid < 0){
	return_msg('管理后台地址不正确');
}
$system=$_G['system'];
$theme = Theme::getThemeById($themeid);
$config = 	Theme::getConfig($themeid);
if(empty($theme['id'])){
	return_msg('管理后台地址不正确');
}

$msg = Worker::gethoutaistats();
if (!empty($msg)) {
	return_msg($msg);
}
// $company = intval($_P['company']);
// if ($system['ruanjian']==3){
// 	$shop=db_find("SELECT * FROM ".tablename(t_shangjia)." WHERE id= '{$company}'");
// 	$shopname=$shop['name'];
// }
if (empty($shopname)){
	if (empty($theme['jubf'])){
		$shopname = $theme['title'];
	}else{
		$shopname = $theme['jubf'];
	}
}
$shopname = mb_substr($shopname,0,8,'utf-8');

//删除重复员工
Worker::WorkerDeleteChongfu($themeid);

if($op=='get'){
	if ($config['showalldata']==0) {
		$noalldata = " and w.themeid =" .$themeid;
	}
	if($system['ruanjian']!=3 || ($system['ruanjian']==3 && $config['showshop']>0)){
	
		$result['code']='200';
		$result['msg']='OK';

		if($system['ruanjian']==3 && $config['showshop']>0){
			$tiaojian = " and (w.company = '{$config['showshop']}' or w.company =0) " ;
			$othercompany = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
			left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid
			WHERE 1=1 and r.themeid ='{$themeid}' and r.status > 0 and (w.company != '{$config['showshop']}' and w.company !=0)" ));
		}

		$sql1 = "SELECT t.name as duiname, w.team, sum(r.newfans) as newfans,sum(r.record) as record,sum(r.recordxx) as recordxx,sum(r.recordzx) as recordzx,sum(r.fee) as fee,sum(r.scansum) as scansum,sum(r.forward) as forward, sum(r.refundfee) as refundfee,sum(r.refund) as refund FROM " . tablename ( t_worker ) . " w
			left join " . tablename ( t_team ) . " t on w.team = t.id
			left join " . tablename ( t_workerreport ) . " r on w.uid = r.workerid and w.themeid = r.themeid
			WHERE 1=1 " . $noalldata . " and w.mobile<>'' " . $tiaojian ;
		$sql2 = " group by w.team ORDER BY record desc,scansum desc,duiname desc";

		// echo $sql1.$sql2;
		$teamlist = db_select($sql1.$sql2);

		foreach ($teamlist as $index => $item) { 
			if (empty($item['duiname'])) {
				$teamlist[$index]['duiname']='无队名';
			}else{
				$teamlist[$index]['duiname']=mb_substr($item['duiname'],0,4,'utf-8');
			}
			if ( empty($item['counts'])) {
				$teamlist[$index]['counts']=0;
			}
			if ( empty($item['scansum'])) {
				$teamlist[$index]['scansum']=0;
			}
			if ( empty($item['forward'])) {
				$teamlist[$index]['forward']=0;
			}
			$teamlist[$index]['counts']=intval($item['record'])+intval($item['recordxx'])-intval($item['refund']);
		}

		$noworker = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
			left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid
			WHERE 1=1 and r.themeid ='{$themeid}' and r.status > 0 and r.workerid = 0 " . $tiaojian . "" ));
		if ($noworker>0) {
			array_push($teamlist,array('counts' => $noworker, 'duiname' => '待认领','scansum'=>0,'forward'=>0));
		}
		if ($othercompany >0 ) {
			array_push($teamlist,array('counts' => $othercompany, 'duiname' => '联盟','scansum'=>0,'forward'=>0));
		}
		$result['dui'] = $teamlist;

		$gsumall = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
			left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid
			WHERE r.themeid ='{$themeid}' and r.status > 0 " . $tiaojian . "" ));
		$gsumall = $gsumall + intval($othercompany);
		$temp_num = 10000;
		$new_num = $gsumall + $temp_num;
		$gsumall = substr($new_num,1,4); //即截取掉最前面的“1”
		$result['cunt']=$gsumall; 


		$sql = "SELECT r.*,r.username as babyname,w.username as wkname,t.name as dui FROM " . tablename ( t_record ) . " as r
			left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid 
			left join " . tablename ( t_team ) . " as t on t.id = w.team
			WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.status > 0
			order by addtime desc limit 10";
		$neworder = db_select ($sql );

		foreach ($neworder as $index => $item) { 
			if (strlen($item['mobile'])==11){
				$neworder[$index]['tel']=substr($item['mobile'] , 0 , 3);
				$neworder[$index]['tel']=$neworder[$index]['tel'] .'****'.substr($item['mobile'] , -4);
			}else{
				$neworder[$index]['tel']=$item['mobile'];
			}
			$neworder[$index]['datetime']=date('H:i',$item['addtime']);
			$neworder[$index]['wkname']=$item['dui']."-".$item['wkname'];
		}
		$result['data'] = $neworder;


	}elseif($system['ruanjian']==3 && $config['showshop']==0){
		$result['code']='200';
		$result['msg']='OK';

		$sql1 = "SELECT w.company,s.name as duiname, sum(r.newfans) as newfans,sum(r.record) as record,sum(r.recordxx) as recordxx,sum(r.recordzx) as recordzx,sum(r.fee) as fee,sum(r.scansum) as scansum,sum(r.forward) as forward, sum(r.refundfee) as refundfee,sum(r.refund) as refund FROM " . tablename ( t_worker ) . " w
			left join " . tablename ( t_shangjia ) . " s on w.company = s.id
			left join " . tablename ( t_workerreport ) . " r on w.uid = r.workerid and w.themeid = r.themeid
			WHERE 1=1 " . $noalldata ;
		$sql2 = " group by w.company ORDER BY record desc,scansum desc,duiname desc";

		$teamlist = db_select($sql1.$sql2);

		// $sql = 'SELECT sum(w.paycounttoday) as today ,sum(w.paycount) as counts,
		// 		sum(w.scansum) as scansum , sum(w.forward) as forward , t.name as duiname FROM ' . tablename(t_worker) . ' as w
		// 		left join ' . tablename(t_shangjia) . ' as t on w.company = t.id
		// 		WHERE 1=1 '.$tiaojian.'
		// 		group by w.company
		// 		ORDER BY t.groupid desc,counts desc,scansum desc,w.company';
		// $teamlist = db_select($sql);
		foreach ($teamlist as $index => $item) { 
			if (empty($item['duiname'])) {
				$teamlist[$index]['duiname']='无名队';
			}else{
				$teamlist[$index]['duiname']=mb_substr($item['duiname'],0,4,'utf-8');
			}
			if ( empty($item['counts'])) {
				$teamlist[$index]['counts']=0;
			}
			if ( empty($item['scansum'])) {
				$teamlist[$index]['scansum']=0;
			}
			if ( empty($item['forward'])) {
				$teamlist[$index]['forward']=0;
			}
			$teamlist[$index]['counts']=intval($item['record'])+intval($item['recordxx'])-intval($item['refund']);
		}

		if($config['showalldata']==0){
			$tiaojian = " and r.themeid = ". $themeid ." ";
		}
		
		$noworker = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
			left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid
			WHERE 1=1 and r.status > 0 and r.workerid = 0 " . $tiaojian . "" ));
		if ($noworker>0) {
			array_push($teamlist,array('counts' => $noworker, 'duiname' => '待认领','scansum'=>0,'forward'=>0));
		}
		$result['dui'] = $teamlist;


		$gsumall = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
			left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid
			WHERE 1=1 and r.status > 0 " . $tiaojian . "" ));
		$temp_num = 10000;
		$new_num = $gsumall + $temp_num;
		$gsumall = substr($new_num,1,4); //即截取掉最前面的“1”
		$result['cunt']=$gsumall; 


		$sql="SELECT o.id, f.username as babyname,f.mobile, wk.username as wkname ,wk.shopyuangong as dui FROM ".tablename($this->ordertable)." as o 
					left join ".tablename($this->fanstable)." as f on o.fansid =  f.id
					left join ".tablename($this->fanstable)." as wk on o.workerid = wk.id
					WHERE paystate=1 
						  ORDER BY o.paytime desc limit 10";

		$sql = "SELECT r.*,r.username as babyname,w.username as wkname,t.name as dui FROM " . tablename ( t_record ) . " as r
			left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid 
			left join " . tablename ( t_shangjia ) . " as t on t.id = w.company
			WHERE 1=1 " . $tiaojian . " and r.status > 0
			order by addtime desc limit 10";
		$neworder = db_select ($sql );

		foreach ($neworder as $index => $item) { 
			if (strlen($item['mobile'])==11){
				$neworder[$index]['tel']=substr($item['mobile'] , 0 , 3);
				$neworder[$index]['tel']=$neworder[$index]['tel'] .'****'.substr($item['mobile'] , -4);
			}else{
				$neworder[$index]['tel']=$item['mobile'];
			}
			$neworder[$index]['datetime']=date('H:i',$item['addtime']);
			$neworder[$index]['wkname']=mb_substr($item['dui'],0,3,'utf-8')."-".$item['wkname'];
		}
		$result['data'] = $neworder;
	}
		die(json_encode($result));
		exit;
}

if($op!=='get'){
define('DEMO_CURL_VERBOSE', false);

# 填写网页上申请的appkey 如 $apiKey="g8eBUMSokVB1BHGmgxxxxxx"
$apiKey = "uQKMo9WXfqhP3gj0weSiC9eB";
# 填写网页上申请的APP SECRET 如 $secretKey="94dc99566550d87f8fa8ece112xxxxx"
$secretKey = "KA9H3hHBCafMcuLI6v3sryOr9AMvHUIH";

# text 的内容为"欢迎使用百度语音合成"的urlencode,utf-8 编码
# 可以百度搜索"urlencode" 
$text = "丽丽，您的客户小丽刚刚下了单，请及时处理！";

// $text2 = iconv("UTF-8", "GBK", $text);
// echo "text length :" . mb_strlen($text2, "GBK") . "\n";


# 发音人选择, 基础音库：0为度小美，1为度小宇，3为度逍遥，4为度丫丫，
# 精品音库：5为度小娇，103为度米朵，106为度博文，110为度小童，111为度小萌，默认为度小美 
$per = 0;
#语速，取值0-15，默认为5中语速
$spd = 5;
#音调，取值0-15，默认为5中语调
$pit = 5;
#音量，取值0-9，默认为5中音量
$vol = 9;
// 下载的文件格式, 3：mp3(default) 4： pcm-16k 5： pcm-8k 6. wav
$aue = 3;

$formats = array(3 => 'mp3', 4 => 'pcm', 5 =>'pcm', 6 => 'wav');
$format = $formats[$aue];

$cuid = "123456PHP";

/** 公共模块获取token开始 */

$auth_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=".$apiKey."&client_secret=".$secretKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $auth_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //信任任何证书
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 检查证书中是否设置域名,0不验证
curl_setopt($ch, CURLOPT_VERBOSE, DEMO_CURL_VERBOSE);
$res = curl_exec($ch);
if(curl_errno($ch))
{
    print curl_error($ch);
}
curl_close($ch);

// echo "Token URL response is " . $res . "\n";
$response = json_decode($res, true);

if (!isset($response['access_token'])){
	echo "ERROR TO OBTAIN TOKEN\n";
	exit(1);
}
if (!isset($response['scope'])){
	echo "ERROR TO OBTAIN scopes\n";
	exit(2);
}

if (!in_array('audio_tts_post',explode(" ", $response['scope']))){
	echo "DO NOT have tts permission\n";
	// 请至网页上应用内开通语音合成权限
	exit(3);
}

$token = $response['access_token'];
// echo "token = $token ; expireInSeconds: ${response['expires_in']}\n\n";
/** 公共模块获取token结束 */

/** 拼接参数开始 **/
// tex=$text&lan=zh&ctp=1&cuid=$cuid&tok=$token&per=$per&spd=$spd&pit=$pit&vol=$vol
$params = array(
	// 'tex' => urlencode($text), // 为避免+等特殊字符没有编码，此处需要2次urlencode。
	'per' => $per,
	'spd' => $spd,
	'pit' => $pit,
	'vol' => $vol,
	'aue' => $aue,
	'cuid' => $cuid,
	'tok' => $token,
	'lan' => 'zh', //固定参数
	'ctp' => 1, // 固定参数
);
$paramsStr =  http_build_query($params);
$url = 'http://tsn.baidu.com/text2audio';
$yxurl = $url . '?' . $paramsStr . "&tex=";
}
 
// echo createMobileUrl('w_daping',array("themeid"=>$themeid,"company"=>$company,"op"=>'get'));
// exit;
if($_G['companyname'] =='新飞驰软件'){
	$return_clicent = get_defined_vars();
return view('/fcworker/fc_daping' , $return_clicent);
}else{
	$return_clicent = get_defined_vars();
return view('/yxworker/w_daping' , $return_clicent);
}
}
}